<?php
// +----------------------------------------------------------------------
// | INPHP
// +----------------------------------------------------------------------
// | Copyright (c) 2021 https://inphp.cc All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://opensource.org/licenses/MIT )
// +----------------------------------------------------------------------
// | Author: lulanyin <me@lanyin.lu>
// +----------------------------------------------------------------------
//                        命令行工具
// +----------------------------------------------------------------------
namespace Inphp\Service\Cmd;

use Inphp\Config;
use Inphp\Service\Service;

class Server
{
    /**
     * 命令对象
     * @var mixed
     */
    public mixed $commend;
    
    public function __construct()
    {
        $argv = $_SERVER['argv'] ?? [];
        if(count($argv) >= 2){
            $params = count($argv) > 2 ? array_slice($argv, 2) : [];
            if(!empty($params)){
                $array = [];
                foreach($params as $param){
                    $arr = explode("=", $param);
                    $array[$arr[0]] = $arr[1] ?? true;
                    $array[$arr[0]] = $array[$arr[0]]=="true" ? true : ($array[$arr[0]]=="false" ? false : $array[$arr[0]]);
                }
                $params = $array;
            }
            //
            $prefix = Config::get("service.cmd.prefix");
            $commend = $prefix.str_replace(".", "\\", $argv[1]);
            if(class_exists($commend))
            {
                //前提
                $middleware_list = Config::get("service.cmd.middleware.before_run");
                $middleware_list = is_array($middleware_list) ? $middleware_list : [];
                Service::processMiddlewares($middleware_list);
                $this->commend = new $commend($params);
                return;
            }
        }
        exit ("not commend".PHP_EOL);
    }
    
    /**
     * 运行
     */
    public function run()
    {
        if(method_exists($this->commend, 'run'))
        {
            $this->commend->run();
            //运行结束
            $middleware_list = Config::get("service.cmd.middleware.after_run");
            $middleware_list = is_array($middleware_list) ? $middleware_list : [];
            Service::processMiddlewares($middleware_list);
            exit("all works done!".PHP_EOL);
        }
        else
        {
            exit($this->commend::class."->run() method not exists");
        }
    }
}